//
//  GroupTopicViewController.swift
//  Venus
//
//  Created by Smith_Yang on 2018/8/5.
//  Copyright © 2018 zhaowang. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import MJRefresh

private let kCellID = "TopicTableViewCell"


class GroupTopicViewController: BaseViewController , PopupMenuDelegate {
    @IBOutlet weak var tableView: UITableView!
    
    var groupModel : TopicGroupModel?
    var pageNo : Int = 1
    var pageSize: Int = 10
    
    var menuView :PopupMenuView?
    var maskView :UIView?
    
    typealias endBlock = (_ success: Bool) -> ()

    fileprivate lazy var topicModelList: [TopicModel] = [TopicModel]()
    
    lazy var searchView:TopicSearchView =  TopicSearchView()

    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI();
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    public func configModel(model:TopicGroupModel){
        
        groupModel = model
        
        title = model.groupName
        
        let dict = ["groupId" : model.groupId,
                    "operatorId" : UserInfo.shareInstance.userModel().id,
                    "userId" : UserInfo.shareInstance.userModel().id,
                    "timestamp" : 1,
                    "sign" : 1]
        NetworkTools.shareInstance.loadData(.get, URLString: kqueryUserIsGroup, parameters: dict) {[weak self] (response, isResult) in
            if !isResult {
                guard let dict = response as? [String  : Any] else { return }
                self?.groupModel?.add = dict["data"] as! Bool
            }
        }
        
        
        
        
    }
    
    public func loadData(){
        
        guard let gModel = groupModel else {
            return
        }
        
        self.hudLoad()
        
        let dict = [
            "userId":String(UserInfo.shareInstance.userModel().id),
            "groupId":String(gModel.id),
            "pageNo":self.pageNo,
            "pageSize":self.pageSize] as [String : Any]
        
        TempNetTool.post( kHost + kqueryGroupTopicList + "".apiF(time: "1", sign: "dd") + "&pageNo=\(self.pageNo)" + "&pageSize=\(self.pageSize)" + "&groupId=\(gModel.id)", parameters: dict, progress: nil, success: { [weak self] (result) in
            self?.tableView.mj_header.endRefreshing()
            self?.tableView.mj_footer.endRefreshing()
            if (self?.pageNo == 1) {
                self?.topicModelList.removeAll()
            }
            if (result != nil) {
                guard let resultDict = result as? [String : NSObject] else { return }
                guard let dataArray = resultDict["data"] as? [NSObject] else { return }
                let topicModels = TopicModel.tmSpeelBreakModelArr(dataArray)
                
                if (topicModels.count < (self?.pageSize)!){
                    self?.tableView.mj_footer.endRefreshingWithNoMoreData()
                }
                self?.topicModelList.append(contentsOf: (topicModels as? [TopicModel])!)
                self?.tableView.reloadData()

            }
            self?.hudHide()
            
            
        }) {[weak self]   (error) in
            self?.hudHide()
            self?.tableView.mj_header.endRefreshing()
            self?.tableView.mj_footer.endRefreshing()
            
        }
        
    }
    
    func deleteTopic(_ topicId: Int, block: endBlock) {
        
        guard let gModel = groupModel else {
            return
        }
        
        self.hudLoad()
        
        let dict = [
            "userId":String(UserInfo.shareInstance.userModel().id),
            "groupId":String(gModel.id),
            "pageNo":self.pageNo,
            "pageSize":self.pageSize] as [String : Any]
        
        TempNetTool.post( kHost + kqueryGroupTopicList + "".apiF(time: "1", sign: "dd") + "&pageNo=\(self.pageNo)" + "&pageSize=\(self.pageSize)", parameters: dict, progress: nil, success: { [weak self] (result) in
            self?.tableView.mj_header.endRefreshing()
            self?.tableView.mj_footer.endRefreshing()
            if (self?.pageNo == 1) {
                self?.topicModelList.removeAll()
            }
            if (result != nil) {
                guard let resultDict = result as? [String : NSObject] else { return }
                guard let dataArray = resultDict["data"] as? [NSObject] else { return }
                let topicModels = TopicModel.tmSpeelBreakModelArr(dataArray)
                
                if (topicModels.count < (self?.pageSize)!){
                    self?.tableView.mj_footer.endRefreshingWithNoMoreData()
                }
                self?.topicModelList.append(contentsOf: (topicModels as? [TopicModel])!)
                self?.tableView.reloadData()
                
            }
            self?.hudHide()
            
            
        }) {[weak self]   (error) in
            self?.hudHide()
            self?.tableView.mj_header.endRefreshing()
            self?.tableView.mj_footer.endRefreshing()
            
        }
        
    }
    
    func joinOrQuitGroup(_ isQuit: Bool) {
        
        guard let gModel = groupModel else {
            return
        }
        
        self.hudLoad()
        
        let dict = [
            "userId":String(UserInfo.shareInstance.userModel().id),
            "groupId":String(gModel.id),
            "isDelete":isQuit] as [String : Any]
        
        TempNetTool.post( kHost + kquitOrJoinGroupList + "".apiF(time: "1", sign: "dd") + "&isDelete=\(isQuit)" + "&groupId=\(gModel.id)", parameters: dict, progress: nil, success: { [weak self] (result) in
            
            if (result != nil) {
                guard let resultDict = result as? [String : NSObject] else { return }
                guard let resCode = resultDict["resCode"] as? String else { return }
                
                if (resCode == "200"){
                    self?.groupModel?.add = !isQuit
                    DispatchQueue.main.async(execute: {
                        self?.menuView = nil
                        if (self?.groupModel?.add == true){
                            self?.showMessageAlert("您已经成功加入该群组")
                        } else {
                            self?.showMessageAlert("您已经成功退出该群组")
                        }
                    })
                }else {
                        self?.showMessageAlert(resultDict["resCode"] as! String)
                }
                
            }
            self?.hudHide()
            
        }) {[weak self]   (error) in
            self?.hudHide()
        }
        
    }
    
    

}


extension GroupTopicViewController:UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.topicModelList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: kCellID, for: indexPath) as! TopicTableViewCell
        cell.configModel(model: self.topicModelList[indexPath.item], index: indexPath)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: false)
        
        let model = self.topicModelList[indexPath.item]
        let vc = TopicDetailViewController()
        vc.configModel(model: model);
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        if (groupModel?.admin)!{
            return true
        }
        return false
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let deleteConfirmVC =  TopicDeleteViewController()
            navigationController?.pushViewController(deleteConfirmVC, animated: true)
            deleteConfirmVC.topicModel = self.topicModelList[indexPath.row];
            deleteConfirmVC.deletedBlock = {(isSuccess) in
                if (isSuccess){
                    self.topicModelList.remove(at: indexPath.row)
                    tableView.deleteRows(at: [indexPath], with: .fade)
                }
            }
        }
    }
    
    
}

extension GroupTopicViewController: UITextFieldDelegate{
    
    func textFieldDidEndEditing(_ textField: UITextField) {
//        schoolViewModel.keyWord = textField.text!
//        self.schoolViewModel.publishSubData.onNext(.mpLoadDataUp)
    }

}


extension GroupTopicViewController {
    fileprivate func setupUI(){
        
        view.addSubview(searchView)
        searchView.snp.makeConstraints { (make) in
            make.top.equalTo(LayoutCommon.navHeight)
            make.left.equalTo(view)
            make.right.equalTo(view)
            make.height.equalTo(45)
        }
        searchView.mytextField.delegate = self
        
        tableView.register(UINib(nibName: "TopicTableViewCell", bundle: nil), forCellReuseIdentifier: kCellID)
        tableView.separatorStyle = .singleLine
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView(frame: CGRect.zero);
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.pageNo = 1
            self.loadData()
        })
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            self.pageNo += 1
            self.loadData()
        })
        tableView.mj_header.beginRefreshing()
        
        
        setupRightAction()
        
        
    }
    
    func setupRightAction() {
        let img=UIImage(named:"nav_more")
        
        let morebutton=UIBarButtonItem(image: img,style: UIBarButtonItem.Style.plain,target:self,action:#selector(moreAction))
        morebutton.tintColor = UIColor.white
        self.navgationBar.topItem?.setRightBarButton(morebutton, animated: false)

    }
    
    func setupCreateMenu() {
        
        if (menuView != nil) {
            if menuView?.superview != nil {
                return
            }
            view.addSubview(maskView!)
            view.addSubview(menuView!)
            
        } else {
            
            maskView = UIView(frame: self.view.bounds);
            let gesture = UITapGestureRecognizer(target: self, action: #selector(dismissMenu))
            maskView?.addGestureRecognizer(gesture)
            view.addSubview(maskView!)
            
            let topicColor = UIColor(red: 23.0 / 255.0, green: 187.0 / 255.0, blue: 254.0 / 255.0, alpha: 1.0)
            let uploadVideoColor = UIColor(red: 225.0 / 255.0, green: 114.0 / 255.0, blue: 114.0 / 255.0, alpha: 1.0)
            let groupColor = UIColor(red: 255.0 / 255.0, green: 107.0 / 255.0, blue: 106.0 / 255.0, alpha: 1.0)
            
            
            if (self.groupModel?.add == true){
                menuView = PopupMenuView(frame: CGRect(x: kScreenW - 93 * kRatio - 10, y: 50 * kRatio, width: 93 * kRatio, height: 89 * kRatio), imageIcons: [["name":kIcon_menu_topic, "color":topicColor], ["name":kIcon_menu_upload, "color":uploadVideoColor], ["name":kIcon_menu_group, "color":groupColor]], title: ["发表话题", "上传视频", "退出群组"])

            } else {
                  menuView = PopupMenuView(frame: CGRect(x: kScreenW - 93 * kRatio - 10, y: 50 * kRatio, width: 93 * kRatio, height: 30 * kRatio), imageIcons: [ ["name":kIcon_menu_group, "color":groupColor]], title: ["加入群组"])
            }
          
            menuView?.menuDelegate = self
            view.addSubview(menuView!)
        }
    }
    
    @objc func dismissMenu() {
        if menuView?.superview != nil {
            menuView?.removeFromSuperview()
        }
        
        if maskView?.superview != nil {
            maskView?.removeFromSuperview()
        }
        
    }
    
    @objc func moreAction() {
        
        setupCreateMenu()

    }
    
    func selectedIndex(index: Int) {
        if index == 1 {
            let addVideoVc = UploadVideoViewController.init(nibName: "UploadVideoViewController", bundle: nil)
            self.navigationController?.pushViewController(addVideoVc, animated: true)
        }
        if index == 0 {
            
            if (groupModel?.add == false){
                joinOrQuitGroup(false)
                
            } else {
                let addTopic = TopicAddNewViewController.init(nibName: "TopicAddNewViewController", bundle: nil)
                self.navigationController?.pushViewController(addTopic, animated: true)

            }
            
        }
        
        if index == 2 {
            
            
            joinOrQuitGroup(true)
        }
        
    }
    
    func showMessageAlert(_ message: String) {
        let alertVC : UIAlertController = UIAlertController.init(title: "", message: message, preferredStyle: .alert)
        let falseAA : UIAlertAction = UIAlertAction.init(title: "确定", style: .cancel, handler: nil)
        
        alertVC.addAction(falseAA)
        self.present(alertVC, animated: true, completion: nil)
    }
    
}
